package com.zdx.yswl.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.linksprite.Jni;
import com.zdx.yswl.App;
import com.zdx.yswl.R;
import com.zdx.yswl.tool.KNetTool;
import com.zdx.yswl.ui.base.BaseActivity;
import com.zdx.yswl.ui.bean.Device;
import com.zdx.yswl.ui.tool.Consts;
import com.zdx.yswl.ui.tool.DevGridAdapter;
import com.zdx.yswl.ui.tool.HttpBindDeviceThread;
import com.zdx.yswl.ui.tool.HttpGetDeviceThread;
import com.zdx.yswl.ui.tool.HttpUnbindDeviceThread;
import com.zdx.yswl.ui.tool.PlayUtil;
import com.zdx.yswl.ui.tool.SqliteDevice;
import com.zdx.yswl.ui.tool.SynchroData;
import com.zdx.yswl.ui.tool.WifiAdmin;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class DevMainActivity extends BaseActivity implements AdapterView.OnItemClickListener
{
    static
    {
        System.loadLibrary("alu");
        System.loadLibrary("play");
    }

    // 登陆的用户名
    private String userName;
    private String devicename;

    // 数据库
    private SqliteDevice sqliteDevice;

    // 设备信息
    String devNumET, devChanET, connChanET, devIP, devPort, devUser, devPwd;
    Button btnApConnect;

    // 设备信息
    public static Device device;// 连接的设备
    public static int channelIndex;// 连接的通道号

    // 设备列表
    public  List<Device> listDevice;
    private GridView gridViewDev;
    private DevGridAdapter devAdapter;

    // imgBack
    private ImageView imgBack;

    // Handler
    private BindDevHandler bindDevHandler;
    private GetDevHandler getDevHandler;
    private UnbindDevHandler unbindDevHandler;

    // 服务相关
    private Intent intentSynchroData;
    
    private WifiAdmin wifiAdmin;
    private String wifiName;

    @Override
    protected void initUi()
    {
        // 设置布局文件
        setContentView(R.layout.dev_activity_main);
        
        wifiAdmin = new WifiAdmin(DevMainActivity.this);

        // 数据库
        sqliteDevice = new SqliteDevice(DevMainActivity.this);
        // sqliteDevice.deleteDatabase(); // 删除数据库

        // 获取用户名
        userName = App.getInstance().getUserName(this);
        Log.e("userId", App.getInstance().getUserName(this));
        String userNameTemp = sqliteDevice.getUserNameFromSql();
        if(userNameTemp != null)
        {
            Log.e("userNameTemp", userNameTemp);
        }
        if(userNameTemp == null)
        {
            sqliteDevice.addUserNameToSql(userName);
        }

        if(!userName.equals(userNameTemp))
        {
            sqliteDevice.delUserFromSql(userNameTemp);
            sqliteDevice.addUserNameToSql(userName);
            sqliteDevice.delAllDevFromSql();
        }

        // 显示设备
        listDevice = new ArrayList<Device>();
        devAdapter = new DevGridAdapter(this, listDevice);
        gridViewDev = (GridView)findViewById(R.id.gridview_dev);
        gridViewDev.setAdapter(devAdapter);
        gridViewDev.setOnItemClickListener(this);
        this.registerForContextMenu(gridViewDev);
        gridViewDev.setOnCreateContextMenuListener(this);

        // 初始化Handler
        bindDevHandler = new BindDevHandler();
        unbindDevHandler = new UnbindDevHandler();
        getDevHandler = new GetDevHandler();

        // 从服务器 获取设备
        HttpGetDeviceThread thread = new HttpGetDeviceThread(userName, getDevHandler);
        thread.start();
        // createDialog("获取设备中，请稍等...", false, true);
        // showTextToast("获取设备中，请稍等...");

        // imgBack获取实例和监听
        imgBack = (ImageView)findViewById(R.id.imgBack);
        imgBack.setOnClickListener(mOnClickListener);

        // 初始化SDK
        boolean initSdk = Jni.init(((App) getApplication()), 9200, Consts.LOG_PATH);
        boolean enableHeler = Jni.enableLinkHelper(true, 3, 10); // 开小助手
        Log.e("enableHeler", enableHeler + "");
        if (initSdk)
        {
            Jni.enableLog(true);
            String version = Jni.getVersion();
            Log.e("SDK_VERSION", version);
        }
        else
        {
            Log.e("initSDK", "initSDK--failed");
        }

        // AP连接的时Device的信息
        devNumET = "A123";
        devChanET = "1"; // 视频源
        connChanET = "1";
        devIP = "";
        devPort = "9101"; // 端口号必须为9101
        devUser = "admin";
        devPwd = "123";

        // AP链接按钮和监听
        btnApConnect = (Button) findViewById(R.id.btnApConnect);
        btnApConnect.setOnClickListener(mOnClickListener);
    }


    // gridView监听
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
    {
        if (!KNetTool.isNetworkConnected(this))
        {
            Toast.makeText(this, "无网络，请检查", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (wifiName != null && wifiName.length() >= 8 && wifiName.substring(1, 8).equals("IPC-H-B"))
        {
        	showTextToast("这是一个不可用的连接");
        }
       
        device = new Device("", 9101, listDevice.get(i).getGid(),
                            listDevice.get(i).getNo(), "admin", "123", 1);
        PlayUtil.setHelperToDevice(device);
        Log.e("设备信息", listDevice.get(i).getGid() + " " + listDevice.get(i).getNo());
        Intent intent = new Intent();
        intent.putExtra("APConnect", false);
        intent.setClass(DevMainActivity.this, PlayActivity.class);
        DevMainActivity.this.startActivity(intent);
    }


    OnClickListener mOnClickListener = new OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            switch (view.getId())
            {
                case R.id.btnApConnect: // AP链接
                {
                	if (!KNetTool.isNetworkConnected(DevMainActivity.this))
                    {
                        Toast.makeText(DevMainActivity.this, "无网络，请检查", Toast.LENGTH_SHORT).show();
                        return;
                    }
                	
                	if (wifiName != null && wifiName.length() >= 8 && wifiName.substring(1, 8).equals("IPC-H-B"))
                	{

	                    int channel = Integer.parseInt(connChanET);
	                    int channelCount = Integer.parseInt(devChanET);
	
	                    if (channel > channelCount)
	                    {
	                        Toast.makeText(DevMainActivity.this, "通道号错误", Toast.LENGTH_SHORT)
	                             .show();
	                    }
	                    else
	                    {
	                        channelIndex = channel - 1;
	
	                        String devFullNo = devNumET;
	                        String group = "";
	                        int yst = -1;
	                        if(!"".equalsIgnoreCase(devFullNo))
	                        {
	                            group = devFullNo.substring(0, 1);
	                            yst = Integer.parseInt(devFullNo.substring(1, devFullNo.length()));
	                        }
	
	                        device = new Device(devIP, Integer.parseInt(devPort), group,
	                                                yst, devUser, devPwd, channelCount);
	                        PlayUtil.setHelperToDevice(device);
	
	                        Intent intent = new Intent();
	                        intent.putExtra("APConnect", true);
	                        intent.setClass(DevMainActivity.this, PlayActivity.class);
	                        DevMainActivity.this.startActivityForResult(intent, Consts.RECODE);
	                    }
                	}
                	else
                	{
                		showTextToast("请先连接设备WiFi");
                	}
                    break;
                }

                case R.id.imgBack: // 返回按钮
                {
                    DevMainActivity.this.finish();
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Intent intent = data;
        if(intent != null)
        {
            boolean isWifiSetSuccess = intent.getBooleanExtra("isWifiSetSuccess", false);
            devicename = intent.getStringExtra("devicename");
            if(isWifiSetSuccess)
            {
                // 初次绑定tag和username相同
                HttpBindDeviceThread httpBindDeviceThread =
                        new HttpBindDeviceThread(userName, devicename, bindDevHandler, devicename);
                httpBindDeviceThread.start();
                createDialog("请稍等...", false, true);
            }
        }
    }

    @Override
    protected void onResume()
    {
    	// TODO Auto-generated method stub
    	super.onResume();
    	wifiName = wifiAdmin.getSSID();
    }
    
    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj)
    {
    }

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj)
    {
    }

    @Override
    protected void initSettings()
    {
    }

    @Override
    protected void saveSettings()
    {
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        // 启动服务
        intentSynchroData = new Intent();
        intentSynchroData.setClass(DevMainActivity.this, SynchroData.class);
        intentSynchroData.putExtra("userName", userName);
        DevMainActivity.this.startService(intentSynchroData);

        Log.e("onStart", "onStart");
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        stopService(intentSynchroData);
        Log.e("onPause", "onPause");
    }

    @Override
    protected void freeMe()
    {
        Jni.deleteLog();
        Jni.deinit();

        sqliteDevice.delAllDevFromSql();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        menu.setHeaderTitle("系统提示");
        menu.add(0, 1, Menu.NONE, "修改设备");
        menu.add(0, 2, Menu.NONE, "删除设备");
        menu.add(0, 3, Menu.NONE, "取消操作");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
        final AdapterView.AdapterContextMenuInfo menuInfo =
                (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        switch (item.getItemId())
        {
            case 3: // 取消
                break;

            case 2: // 删除
                if (!KNetTool.isNetworkConnected(DevMainActivity.this))
                {
                    Toast.makeText(DevMainActivity.this, "无网络，请检查", Toast.LENGTH_SHORT).show();
                    break;
                }

                Toast.makeText(DevMainActivity.this, "删除设备", Toast.LENGTH_SHORT).show();

                devicename = listDevice.get(menuInfo.position).getFullNo();
                Log.e("dev grid case 2 删除", userName + ":" + devicename);

                HttpUnbindDeviceThread httpUnbindDeviceThread =
                        new HttpUnbindDeviceThread(userName, devicename, unbindDevHandler);
                httpUnbindDeviceThread.start();

                listDevice.remove(menuInfo.position);
                devAdapter.notifyDataSetChanged();
                createDialog("请稍等...", false, true);
                break;

            case 1:
                if (!KNetTool.isNetworkConnected(DevMainActivity.this))
                {
                    Toast.makeText(DevMainActivity.this, "无网络，请检查", Toast.LENGTH_SHORT).show();
                    break;
                }

                AlertDialog.Builder dialogRenameDevBuilderT = new AlertDialog.Builder(DevMainActivity.this);

                View viewRenameDev = View.inflate(DevMainActivity.this,
                                                  R.layout.dialog_rename_dev, null);
                final EditText edtTag = (EditText) viewRenameDev.findViewById(R.id.edt_tag);
                Button btnYes = (Button)viewRenameDev.findViewById(R.id.btn_yes);
                Button btnNo = (Button)viewRenameDev.findViewById(R.id.btn_no);

                final AlertDialog dialogRenameDevT = dialogRenameDevBuilderT.create();
                dialogRenameDevT.setView(viewRenameDev);

                btnYes.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        // 更改tag的操作
                        devicename = listDevice.get(menuInfo.position).getFullNo();
                        String tag = edtTag.getText().toString().trim();


                        if(tag == null || tag.equals(""))
                        {
                            Toast.makeText(DevMainActivity.this, "修改失败，设备标签名不能为空",
                                           Toast.LENGTH_SHORT).show();
                            return;
                        }

                        // 保存tag的值到对应的Device中
                        listDevice.get(menuInfo.position).setTag(tag);
                        Log.e("dev grid case 3 修改", userName + ":" + devicename + ":" + tag);

                        HttpBindDeviceThread httpBindDeviceThread =
                                new HttpBindDeviceThread(userName, devicename, bindDevHandler, tag);
                        httpBindDeviceThread.start();

                        // 无论绑定是否成功，加入本地数据库，并将绑定位标记为未绑定
                        sqliteDevice.addDevToSql(devicename, 0, tag);

                        dialogRenameDevT.dismiss();
                    }
                });

                btnNo.setOnClickListener(new OnClickListener()
                {
                    @Override public void onClick(View v)
                    {
                        // 取消操作，什么也不做
                        dialogRenameDevT.dismiss();
                    }
                });

                /* // 自动弹出软键盘，这里不使用，如果需要请去掉注释
                dialogRenameDevT.setOnShowListener(new DialogInterface.OnShowListener()
                {
                    public void onShow(DialogInterface dialog)
                    {
                        InputMethodManager imm =
                                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(edtTag,
                                          InputMethodManager.SHOW_IMPLICIT);
                    }
                }); */

                dialogRenameDevT.show();
                break;

            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }

    /** 获取设备Handler **/
    private class GetDevHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);

            // 去掉进度条
            dismissDialog();

            Bundle bundle = msg.getData();
            int code = bundle.getInt("code");
            Log.e("code get", "" + code);

            if(code == 200) // 请求成功
            {
                JSONObject jsonObject;
                JSONArray jsonObjectData = null;

                String info = bundle.getString("info");
                Log.e("DevMainActivity", info);

                try
                {
                    if(info != null)
                    {
                        listDevice.clear();
                        jsonObject = new JSONObject(info);
                        jsonObjectData = jsonObject.getJSONArray("data");
                        for(int i = 0; i < jsonObjectData.length(); i++)
                        {
                            JSONObject jsonObjectDevice = jsonObjectData.getJSONObject(i);
                            String userId = jsonObjectDevice.getString("userId");
                            String deviceId = jsonObjectDevice.getString("deviceId");
                            String addTime = jsonObjectDevice.getString("addTime");
                            String id = jsonObjectDevice.getString("id");
                            String tag = jsonObjectDevice.getString("tag");
                            Log.e("Devices " + i, "UserId:" + userId +
                                                  "  DevId:" + deviceId +
                                                  "  AddTime:" + addTime +
                                                  "  Id:" + id +
                                                  "  Tag:" + tag);
                            Device deviceTemp =
                                    new Device("", 9101,
                                               deviceId.substring(0, 1),
                                               Integer.parseInt(deviceId.substring(1, deviceId.length())),
                                               "admin", "123", 1);

                            if(tag == null)
                            {
                                deviceTemp.setTag(userId);
                                Log.e("tag get", "tag is null");
                            }
                            else
                            {
                                deviceTemp.setTag(tag);
                                Log.e("tag get", tag);
                            }

                            listDevice.add(deviceTemp);
                            sqliteDevice.addDevToSql(deviceId, 1, tag);
                            devAdapter.notifyDataSetChanged();
                        }
                    }
                }
                catch(JSONException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                 showTextToast("当前未绑定任何设备");
                // if(listDevice.size() != 0)
                // {
                //     listDevice.clear();
                // }

                // listDevice.addAll(sqliteDevice.getLsitDevFromSql());
                // devAdapter.notifyDataSetChanged();
            }
        }
    }

    /** 绑定设备Handler **/
    private class BindDevHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);

            dismissDialog();

            Bundle bundle = msg.getData();

            int code = bundle.getInt("code");
            Log.e("code bind", "" + code);

            String tag = bundle.getString("tag");

            if(code == 200 && bundle.getBoolean("status"))
            {
                // 绑定成功， 将绑定位标记为绑定
                sqliteDevice.addDevToSql(devicename, 1, tag);
                HttpGetDeviceThread threadATemp = new HttpGetDeviceThread(userName, getDevHandler);
                listDevice.clear(); // 先清除链表中的设备
                threadATemp.start();
                createDialog("获取设备中，请稍等...", false, true);
            }
            else
            {
                devAdapter.notifyDataSetChanged();

                // 绑定失败，继续申请绑定
                HttpBindDeviceThread httpBindDeviceThread =
                        new HttpBindDeviceThread(userName, devicename, bindDevHandler, tag);
                httpBindDeviceThread.start();
            }
        }
    }

    /** 解除绑定Handler **/
    private class UnbindDevHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);

            dismissDialog();

            Bundle bundle = msg.getData();
            int code = bundle.getInt("code");
            Log.e("code unbind", "" + code);
            if(code == 200 && bundle.getBoolean("status"))
            {
                // Toast.makeText(DevMainActivity.this, "设备解绑成功", Toast.LENGTH_SHORT).show();
                sqliteDevice.delDevFromSql(devicename);
            }
            else
            {
                HttpUnbindDeviceThread httpUnbindDeviceThread =
                        new HttpUnbindDeviceThread(userName, devicename, unbindDevHandler);
                httpUnbindDeviceThread.start();
            }
        }
    }
}
